package com.sms.templateservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sms.common.result.Result;
import com.sms.common.result.ResultCode;
import com.sms.templateservice.entity.SmsTemplate;
import com.sms.templateservice.entity.SmsTemplateLog;
import com.sms.templateservice.mapper.SmsTemplateMapper;
import com.sms.templateservice.mapper.SmsTemplateLogMapper;
import com.sms.templateservice.service.SmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class SmsTemplateServiceImpl extends ServiceImpl<SmsTemplateMapper, SmsTemplate> implements SmsTemplateService {
    
    @Autowired
    private SmsTemplateLogMapper smsTemplateLogMapper;
    
    @Override
    @Transactional
    public Result<String> applyTemplate(SmsTemplate template) {
        // 参数校验
        if (StrUtil.isBlank(template.getTemplateName()) || StrUtil.isBlank(template.getTemplateContent())) {
            return Result.error(ResultCode.PARAM_ERROR, "模板名称和内容不能为空");
        }
        
        // 设置申请状态
        template.setAuditStatus(0); // 待审核
        template.setEnabled(0); // 默认禁用
        template.setApplyTime(LocalDateTime.now());
        
        // 保存模板
        save(template);
        
        // 记录日志
        SmsTemplateLog log = new SmsTemplateLog();
        log.setTemplateId(template.getId());
        log.setOperationType(1); // 申请
        log.setOperatorId(template.getApplicantId());
        log.setOperationDesc("申请模板：" + template.getTemplateName());
        log.setOperationTime(LocalDateTime.now());
        smsTemplateLogMapper.insert(log);
        
        return Result.success("模板申请成功");
    }
    
    @Override
    @Transactional
    public Result<String> auditTemplate(Long templateId, Integer auditStatus, String auditOpinion, Long auditorId) {
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return Result.error(ResultCode.PARAM_ERROR, "模板不存在");
        }
        
        // 更新审核状态
        template.setAuditStatus(auditStatus);
        template.setAuditOpinion(auditOpinion);
        template.setAuditorId(auditorId);
        template.setAuditTime(LocalDateTime.now());
        
        updateById(template);
        
        // 记录日志
        SmsTemplateLog log = new SmsTemplateLog();
        log.setTemplateId(templateId);
        log.setOperationType(2); // 审核
        log.setOperatorId(auditorId);
        log.setBeforeStatus("待审核");
        log.setAfterStatus(auditStatus == 1 ? "审核通过" : "审核拒绝");
        log.setOperationDesc("审核模板：" + template.getTemplateName() + "，意见：" + auditOpinion);
        log.setOperationTime(LocalDateTime.now());
        smsTemplateLogMapper.insert(log);
        
        return Result.success("审核完成");
    }
    
    @Override
    @Transactional
    public Result<String> toggleTemplate(Long templateId, Integer enabled) {
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return Result.error(ResultCode.PARAM_ERROR, "模板不存在");
        }
        
        // 只有审核通过的模板才能启用
        if (enabled == 1 && template.getAuditStatus() != 1) {
            return Result.error(ResultCode.PARAM_ERROR, "只有审核通过的模板才能启用");
        }
        
        template.setEnabled(enabled);
        updateById(template);
        
        // 记录日志
        SmsTemplateLog log = new SmsTemplateLog();
        log.setTemplateId(templateId);
        log.setOperationType(enabled == 1 ? 3 : 4); // 3-启用，4-禁用
        log.setBeforeStatus(template.getEnabled() == 1 ? "启用" : "禁用");
        log.setAfterStatus(enabled == 1 ? "启用" : "禁用");
        log.setOperationDesc((enabled == 1 ? "启用" : "禁用") + "模板：" + template.getTemplateName());
        log.setOperationTime(LocalDateTime.now());
        smsTemplateLogMapper.insert(log);
        
        return Result.success(enabled == 1 ? "模板启用成功" : "模板禁用成功");
    }
    
    @Override
    public Result<SmsTemplate> getTemplateDetail(Long templateId) {
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return Result.error(ResultCode.PARAM_ERROR, "模板不存在");
        }
        return Result.success(template);
    }
    
    @Override
    public Result<Object> getTemplateList(Integer pageNum, Integer pageSize, String templateName, Integer templateType, Integer auditStatus) {
        Page<SmsTemplate> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsTemplate> queryWrapper = new QueryWrapper<>();
        
        if (StrUtil.isNotBlank(templateName)) {
            queryWrapper.like("template_name", templateName);
        }
        if (templateType != null) {
            queryWrapper.eq("template_type", templateType);
        }
        if (auditStatus != null) {
            queryWrapper.eq("audit_status", auditStatus);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<SmsTemplate> result = page(page, queryWrapper);
        return Result.success(result);
    }
} 